import 'package:mi_mang_flutter/api/user_api.dart';
import 'package:mi_mang_flutter/model/user_info_model.dart';
import 'package:mi_mang_flutter/network/response_data.dart';
import 'package:mi_mang_flutter/provider/view.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';

/// 用户信息管理,主要用途: 控制登录前后本地用户数据刷新
class UserProvider extends ViewModel<ResponseData<UserInfoModel>> {
  UserInfoModel? _user;
  UserInfoModel? get user {
    _user = getUserFromLocalStorage();
    if (data?.data != null) {
      _user = data?.data;
    }
    return _user;
  }

  void setUser(UserInfoModel? user) {
    _user = user;
    data?.data = user;
    notifyListeners();
  }

  @override
  Future<ResponseData<UserInfoModel>> Function() get future => () async {
        ResponseData<UserInfoModel> response =
            (await UserApi.getUserCurrent(false));
        SpUtil.putObject(SPKeys.USER_INFO, response.data);
        return response;
      };

  /// 判断用户资料是否完整
  bool isUserInfoComplete() {
    if (this.user!.realName == null) {
      return false;
    }
    return true;
  }

  /// 获取本地登录用户信息
  UserInfoModel? getUserFromLocalStorage() {
    UserInfoModel? user;
    var userInfoMap = SpUtil.getObject(SPKeys.USER_INFO);
    if (userInfoMap != null) {
      user = UserInfoModel.fromJson(userInfoMap);
    }
    return user;
  }

  /// 获取本地登录用户信息
  void updateUserInfo({
    String? avatar,
    DateTime? birthday,
    String? email,
    String? mobile,
    String? nickName,
    int? sex,
    String? signature,
    String? theme,
  }) {
    assert(
        avatar == null ||
            birthday == null ||
            email == null ||
            mobile == null ||
            nickName == null ||
            sex == null ||
            signature == null ||
            theme == null,
        '参数不能全部为空');

    UserInfoModel? user = getUserFromLocalStorage();
    UserApi.updateUserInfo(
      avatar ?? user!.avatar,
      birthday ?? user!.birthday,
      email ?? user!.email,
      mobile ?? user!.mobile,
      nickName ?? user!.nickName,
      sex ?? user!.sex,
      signature ?? user!.signature,
      theme ?? user!.theme,
    ).then((val) {
      init();
    });
  }
}
